package com.chisheng.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

/**
 * SwaggerConfig
 * <p>
 * home page: http://localhost:8080/swagger-ui.html
 *
 * @author chisheng
 */
@Data
@Configuration
@EnableSwagger2  // 开启 Swagger2 的自动配置
@ConfigurationProperties(prefix = "swagger")
public class SwaggerConfig {

    /**
     * 手动配置是否开启 Swagger
     */
    private boolean enabled;

    @Bean
    @SuppressWarnings("all")
    public Docket defaultDocket(Environment environment) {

        /* Swagger 实例 Bean 是Docket，所以通过配置 Docket 实例来配置 Swagger */

        // 设置要显示 Swagger 的环境
        final Profiles profiles = Profiles.of("dev", "test");

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("defaultGroup")
                .apiInfo(this.getApiInfo())
                .enable(enabled)  // 配置是否启用 Swagger
                // .enable(environment.acceptsProfiles(profiles))  // 判断当前是否处于该环境
                .select()  // 通过 select() 方法，去配置扫描接口
                .apis(RequestHandlerSelectors.basePackage("com.chisheng.controller"))
                // .paths(PathSelectors.ant("/chisheng/**"))  // 配置通过 path 过滤
                .build();
    }

    /**
     * 可以通过 apiInfo() 属性配置文档信息
     *
     * @return ApiInfo
     */
    public ApiInfo getApiInfo() {

        /* public Contact(String name, String url, String email) {
         *     // 联系人名字
         *     this.name = name;
         *     // 联系人访问链接
         *     this.url = url;
         *     // 联系人邮箱
         *     his.email = email;
         * } */

        final Contact contact = new Contact(
                "Chisheng", "https://www.gitee.com/yunlm", "gndlwccw@163.com"
        );

        /* public ApiInfo(
         *  String title,
         *  String description,
         *  String version,
         *  String termsOfServiceUrl,  // terms of service
         *  Contact contact,
         *  String license,
         *  String licenseUrl,
         *  Collection<VendorExtension> vendorExtensions) */

        return new ApiInfo(
                "SwaggerLearn",
                "Swagger learn demo code",
                "1.0",
                "https://gitee.com/yunlm/codelabs",
                contact,
                "Apache 2.0",
                "https://www.apache.org/licenses/LICENSE-2.0.html",
                List.of()
        );
    }

}
